package com.hibernate.key;

import java.io.Serializable;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.hibernate.key.Account_2.AccountPk;

public class QueryAccount_2Entity {

	private static SessionFactory factory = new Configuration().configure().buildSessionFactory();
	private static Session session;

	public static void main(String[] args) {
		//QueryAccount();
		SaveAccount();
		//GetAccount();
	}
	
	public static void GetAccount(){
		session = factory.openSession();
		AccountPk accpk = new AccountPk();
		accpk.setCode("002");
		accpk.setNumber(100);
		Account_2 ac = (Account_2) session.get(Account_2.class, accpk);
		System.out.println("Account:Code=" + ac.getId().getCode() + ", Number=" + ac.getId().getNumber() + 
				", description=" + ac.getDescription());
		session.close();
	}
	
	public static void SaveAccount(){
		session = factory.openSession();
		session.beginTransaction();
		Account_2 acc = new Account_2();
		acc.setDescription("test save compound key version2.");
		AccountPk accpk = new AccountPk();
		accpk.setCode("003");
		accpk.setNumber(200);
		acc.setId(accpk);
		session.save(acc);
		session.getTransaction().commit();
		session.close();
	}
	
	
	public static void QueryAccount() {
		// QueryEntity
		session = factory.openSession();
		// Query q = session.createQuery("from Message");
		// Query q = session.createQuery("from Message where id > :id");
		Query q = session.createQuery("from Account");
		List l = q.list();

		for (Object obj : l) {
			// TODO Fix Error from obj is Account 
			Account_2 acc = (Account_2) obj;
			Serializable id = session.getIdentifier(acc);
			Account_2.AccountPk pk = (Account_2.AccountPk) id;
			System.out.println("Account:code=" + pk.getCode() + ", number=" + pk.getNumber() + ", description="
					+ acc.getDescription());
		}

		if (l.size() > 0) System.out.println("List size=" + l.size());
		else System.out.println("Empty List");

		session.close();
	}

}
